package com.mt.jobhandler;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONUtil;
import com.mt.RedisUtils;
import com.mt.constants.Result;
import com.mt.enums.LikeStatus;
import com.mt.feign.FilmApiProvider;
import com.mt.pojo.CommentLike;
import com.mt.pojo.Film;
import com.mt.pojo.FilmComment;
import com.xxl.job.core.handler.annotation.XxlJob;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.mt.constants.SYS.COMMENT_LIKE;
import static com.mt.constants.SYS.TOP_FILM_CACHE;

/**
 * @author Wang
 * @Description TODO
 * @date 2021/3/10-23:52
 */
@Component
@Slf4j
public class myhandler {
    private static Logger logger = LoggerFactory.getLogger(myhandler.class);
    @Resource
    RedisUtils redisUtils;

    @Resource
    FilmApiProvider filmApiProvider;

    @XxlJob("refreshFilmCacheHandler")
    public void refreshFilmCache()throws Exception {
        try {
            for (int i = 0; i < 3; i++) {
                Result result = filmApiProvider.getTopFilm();
                List<Film>cacheFilms = (List<Film>) result.getData();
                logger.info(cacheFilms.toString());
                JSONConfig jsonConfig = JSONConfig.create()
                        .setDateFormat("yyyy-MM-dd")
                        .setIgnoreNullValue(false);
                JSON s = JSONUtil.parse(cacheFilms, jsonConfig);
                redisUtils.set(TOP_FILM_CACHE, s.toString(), 6L, TimeUnit.HOURS);
                if (!cacheFilms.isEmpty()) {
                    logger.info("缓存电影信息成功 !!");
                    break;
                } else {
                    logger.error("重新进行缓存");
                }
            }
        } catch (Exception e) {
            logger.error("启动缓存失败:" + e.toString());
        }

    }


    @XxlJob("calculateAvgScoreHandler")
    public void calculateAvgScore() throws Exception{
        //根据最近评论时间和电影结束时间进行计算
        //todo 根据创建时间筛选电影,只更新最近有评论的电影
//        commentMapper.selectList()
        FilmComment comment = new FilmComment();
        comment.setScore(13);
        System.out.println( comment.getScore()+"ceshi");

    }

    @XxlJob("saveCommentLike2Db")
    public void saveCommentLike2Db() throws Exception {
        Map<String, Object> hashKeys = redisUtils.getHashKeys(COMMENT_LIKE);
        List<CommentLike> likeList = CollUtil.newArrayList();
        Map<Integer, Integer> likeMap = CollUtil.newHashMap();
        hashKeys.keySet().forEach(key -> {
            String[] split = key.split("::");
            String likedUserId = split[0];
            int likedComment = Integer.parseInt(split[1]);
            int likeStatus = (Integer) hashKeys.get(key);
            CommentLike like = new CommentLike(likedUserId, likedComment, likeStatus);
            //统计点赞总数-->去更新电影数量
            if (likeStatus == LikeStatus.LIKE.getCode()) {
                if (likeMap.containsKey(likedComment)) {
                    Integer num = likeMap.get(likedComment);
                    likeMap.replace(likedComment, num + 1);
                } else {
                    likeMap.put(likedComment, 1);
                }
            }else {
                if (likeMap.containsKey(likedComment)) {
                    Integer num = likeMap.get(likedComment);
                    likeMap.replace(likedComment, num - 1);
                }else {
                    likeMap.put(likedComment, -1);
                }
            }
            likeList.add(like);
        });
        //持久化点赞数据
        if (! likeList.isEmpty()){
            boolean save = filmApiProvider.saveLikeList2Db(likeList);
        }
        //统计点赞总数
        if (! likeMap.isEmpty()){
            boolean count = filmApiProvider.countLikeTotal(likeMap);
        }

    }
}
